package edu.cs.usask.ca.silver.plugin.rcp.sourceprovider;

import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.Logger;
import org.eclipse.ui.AbstractSourceProvider;
import org.eclipse.ui.ISources;

import edu.cs.usask.ca.silver.businesslogic.ids.BaseId;
import edu.cs.usask.ca.silver.businesslogic.ids.SilverIDVisitor;
import edu.cs.usask.ca.silver.plugin.rcp.jobs.LoggerReportScheduler;

/**
 * We keep plug-in level states in SilverUISourceProvider. It stores dynamic
 * states. For example: user login states, projectView selected states etc. It
 * is recommended to store plug-in wide parameters here than leaving them around
 * different places
 * 
 * @author Yudi Xue
 * 
 */
public class SilverUISourceProvider extends AbstractSourceProvider {

	// provided source name
	public final static String PROJECTVIEW_SELECTED_STATE = "edu.cs.usask.ca.silver.plugin.rcp.sourceprovider.projectview.selected";
	public final static String SESSION_STATE = "edu.cs.usask.ca.silver.plugin.rcp.sourceprovider.sessionState";

	public final static String SELECTED_USER = "USER";
	public final static String SELECTED_GROUP = "GROUP";
	public final static String SELECTED_MP = "MP";
	public final static String SELECTED_MV = "MV";
	public final static String SELECTED_SC = "SC";
	public final static String SELECTED_S = "S";

	private final static String LOGGED_IN = "loggedIn";
	private final static String LOGGED_OUT = "loggedOut";

	private static Logger logger = Logger
			.getLogger(SilverUISourceProvider.class);
	private HashMap<String, String> property_map = new HashMap<String, String>();

	@Override
	public void dispose() {
	}

	@SuppressWarnings("unchecked")
	@Override
	public Map<String, String> getCurrentState() {
		return (Map<String, String>) property_map.clone();
	}

	@Override
	public String[] getProvidedSourceNames() {
		return new String[] { PROJECTVIEW_SELECTED_STATE, SESSION_STATE };
	}

	public void saveProjectViewSelection(BaseId id) {
		SilverIDVisitor v = new SilverUISourceProviderSilverIDVisitorImpl(this,
				property_map);
		try {
			id.accept(v);
		} catch (Exception e1) {
			LoggerReportScheduler.scheduleErrorLogging(logger,"error in SilverUISourceProvider", e1);
		}
	}

	public void fireSourceChangedForProjectViewSelectedState(String value) {
		fireSourceChanged(ISources.WORKBENCH, PROJECTVIEW_SELECTED_STATE, value);
	}

	public void setLoggedIn(boolean loggedIn) {
		@SuppressWarnings("unused")
		String previous_state = loggedIn ? property_map.put(SESSION_STATE,
				LOGGED_IN) : property_map.put(SESSION_STATE, LOGGED_OUT);
		fireSourceChanged(ISources.WORKBENCH, SESSION_STATE,
				property_map.get(SESSION_STATE));
	}

}
